package com.zkingsoft.task;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zkingsoft.actions.dingding.DDRobotController;
import com.zkingsoft.dao.ProjectDao;
import com.zkingsoft.dingding.OApiException;
import com.zkingsoft.dingding.auth.AuthHelper;
import com.zkingsoft.model.Project;
import com.zkingsoft.plugin.util.LogUtil;
import com.zkingsoft.plugin.util.StringUtils;
import com.zkingsoft.services.TaskService;

/**
 * 定时器
 * 
 * @Title: AnnotationQuartz.java  
 * @description
 * @author 罗凯
 * @email 18075895212@qq.com
 * @date 2016年8月17日 上午9:26:43
 */
@Component
public class AnnotationQuartz {
	Logger log = Logger.getLogger(AnnotationQuartz.class);
	@Resource
	private TaskService taskService;

	@Autowired
	private ProjectDao projectDao;

	@Resource
	private DDRobotController robotController;

	/**
	 * @Description:每天十二点检查任务是否过期
	 * @author:dingchuan 返回类型 void
	 * @date 2016年12月5日
	 */
	@Scheduled(cron = "0 0 0 ? * *")
	public void changeTaskStatus() {
		LogUtil.inof(AnnotationQuartz.class, "开始调用了任务定时器.......");
		taskService.taskStatusTimer();
		LogUtil.inof(AnnotationQuartz.class, "结束调用了任务定时器.......");
	}

	/**
	 * @Description:每个两个小时更新一次jsapi_ticket
	 * @author:dingchuan 返回类型 void
	 * @throws OApiException
	 * @date 2016年12月7日
	 */
	@Scheduled(cron = "0 0 0/2 * * ?")
	public void updateJsAPiTicket() throws OApiException {
		LogUtil.inof(AnnotationQuartz.class, "开始调用了更新jsapi_ticket定时器.......");
		AuthHelper.getJsapiTicket(AuthHelper.getAccessToken());
		LogUtil.inof(AnnotationQuartz.class, "结束调用了更新jsapi_ticket定时器.......");
	}

	/**
	 * @Description:工作日上午9:30检查任务为未完成的，并发送消息
	 * @author:dingchuan 返回类型 void
	 * @throws Exception
	 * @throws OApiException
	 * @date 2016年12月15日
	 */
	//@Scheduled(cron = "0 30 9 ? * MON-FRI")
	// @Scheduled(cron = "0 59 9 ? * *")
	public void sendTaskNoFinishedOa() throws Exception {
		LogUtil.inof(AnnotationQuartz.class, "开始调用了发送未完成任务消息通知.......");
		taskService.SendNoFinishedTaskOa();
		robotController.sendProjectStatus();
		LogUtil.inof(AnnotationQuartz.class, "结束调用了发送未完成任务消息通知.......");
	}

	@Scheduled(cron = "0 0/5 * * * ?")
	public void checkAppRunState() throws Exception {
		log.info("开始检查应用状态");
		Project project = new Project();
		project.setStatus("正式上线");
		List<Project> projectList = projectDao.selectByModel(project);
		for (Project project2 : projectList) {
			if (StringUtils.isNotBlank(project2.getUrl())) {
				checkNginxIsWork(project2);
			}
		}
	}

	// 项目监控信息
	private static String proJK = "{\"msgtype\":\"markdown\"," + "\"markdown\":{\"title\":\"项目监控平台警告 \","
			+ "\"text\":\"# 【监控异常】- PRONAME \n > ## 监控信息：STATUS \n  ## 请相关人员及时处理 \"}}";

	private boolean checkNginxIsWork(Project project) throws Exception {
		URL realUrl = new URL(project.getUrl());
		try {
			
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			HttpURLConnection httpUrlConnection = (HttpURLConnection) connection;
			// 建立实际的连接
			httpUrlConnection.connect();
			httpUrlConnection.setConnectTimeout(1000*60);
			httpUrlConnection.setReadTimeout(1000*60);
			httpUrlConnection.connect();
			String code = new Integer(httpUrlConnection.getResponseCode()).toString();
			String message = httpUrlConnection.getResponseMessage();
			log.info("getResponseCode code =" + code);
			log.info("getResponseMessage message =" + message);
			if (!code.equals("200") && !code.equals("302") ) {
				// 异常
				String msg = new String(proJK).replaceAll("PRONAME", project.getProjName()).replaceAll("STATUS",
						"访问: " + realUrl + " \n   返回状态码：" + code);
				robotController.sendMsg(msg);
			}
		} catch (Exception e) {
			// 异常
			String msg = new String(proJK).replaceAll("PRONAME", project.getProjName()).replaceAll("STATUS",
					"访问: " + realUrl + " \n    " + e.getMessage());
			robotController.sendMsg(msg);
		}
		return false;
	}

}